package helper;

import java.util.Date;
import java.util.Random;

import play.Logger;
import play.cache.Cache;
import play.libs.Codec;
import play.libs.Images;
/***
 * 
 * @author eliotLiu
 *
 */
public class CaptchaHelp {

	private final static String NOISE_COLOR = "#ffffff";
	private final static String CAPTCHA_CHARS = "0123456789";
	private final static int CAPTCHA_CHAR_COUNT = 4;
	private final static String CACHE_EXPIRES = "30mn";	

	public static Images.Captcha captcha(String id, int width, int height) {
		Images.Captcha captcha = Images.captcha(width, height);
		captcha.setBackground(NOISE_COLOR);
		String code = captcha.getText(CAPTCHA_CHAR_COUNT, CAPTCHA_CHARS);
		Cache.set(id, code.toLowerCase(), CACHE_EXPIRES);
		return captcha;
	}

	
	public static String generaterCaptchaId() {
		return Codec.UUID();
	}
	
	public static boolean check(String captchaId, String captchaCode) {
		if (isNullOrEmpty(captchaCode) || isNullOrEmpty(captchaId))
			return false;
		return captchaCode.equalsIgnoreCase(Cache.get(captchaId) + "");
	}

	public static boolean isNullOrEmpty(String s) {
		return null == s || 0 == s.trim().length();
	}
}